import net.lingala.zip4j.core.ZipFile;
import net.lingala.zip4j.exception.ZipException;
import org.apache.commons.io.DirectoryWalker;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * Created by eahn on 01/11/13.
 */
public class ZipUncompressorWalker extends DirectoryWalker<File> {

    private static Logger logger = LoggerFactory.getLogger(ZipUncompressorWalker.class);

    protected File dir;
    protected String dirPrefix;


    public ZipUncompressorWalker(File dir) {
        super();

        this.dir = dir;

        this.dirPrefix = dir.getAbsolutePath();
    }

    public List<File> start() throws IOException {

        List<File> results = new ArrayList<File>();
        walk(dir, results);
        return results;
    }


    protected void handleFile(File file, int depth, Collection<File> results) {

        if (file.getAbsolutePath().endsWith(".zip")) {
            File out = file.getParentFile();
            if (out.isDirectory()) {

                unzip(file, out);
                results.add(file);

            } else {

                logger.error("Can not unzip file to " + out.getAbsolutePath());
            }
        }


    }

    public static void unzip(File file, File out) {
        try {
            logger.debug("Unzipping " + file.getAbsolutePath() + " to " + out.getAbsolutePath());

            ZipFile zipFile = new ZipFile(file);
            zipFile.extractAll(out.getAbsolutePath());

        } catch (ZipException e) {
            logger.error("Error unzipping", e);
        }
    }


}
